import React, { useState, useEffect } from 'react'
import { View, Text, Button, Textarea } from '@tarojs/components'
import Taro from '@tarojs/taro'
import { useAppContext } from '../../store'
import { CloudDataManager } from '../../utils/cloud'
import { DishRating } from '../../types'
import { pointsUtils } from '../../utils/pointsUtils'
import './index.scss'

interface RatingProps {
  dishId: string;
  dishName: string;
  onRatingSubmit?: (rating: DishRating) => void;
  showExistingRatings?: boolean;
}

const DishRatingComponent: React.FC<RatingProps> = ({ 
  dishId, 
  dishName,
  onRatingSubmit,
  showExistingRatings = false
}) => {
  const { state } = useAppContext()
  const [userRating, setUserRating] = useState<number | null>(null)
  const [comment, setComment] = useState('')
  const [existingRatings, setExistingRatings] = useState<DishRating[]>([])
  const [userHasRated, setUserHasRated] = useState(false)
  const [loading, setLoading] = useState(false)
  const [showRatingForm, setShowRatingForm] = useState(false)
  
  // 初始化时加载评价
  useEffect(() => {
    fetchRatings()
  }, [dishId])
  
  // 获取评价数据
  const fetchRatings = async () => {
    try {
      // 获取菜品的所有评价
      const ratings = await CloudDataManager.getAllData('ratings', { dishId }) as DishRating[]
      
      // 排序：按时间倒序
      const sortedRatings = ratings.sort((a, b) => 
        new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime()
      )
      
      setExistingRatings(sortedRatings)
      
      // 检查当前用户是否已评价
      if (state.currentUser) {
        const userRating = ratings.find(rating => rating.userId === state.currentUser?.id)
        if (userRating) {
          setUserHasRated(true)
          setUserRating(userRating.rating)
          setComment(userRating.comment || '')
        }
      }
    } catch (error) {
      console.error('获取评价失败:', error)
      Taro.showToast({
        title: '获取评价失败',
        icon: 'none'
      })
    }
  }
  
  // 处理评分点击
  const handleRatingClick = (rating: number) => {
    setUserRating(rating)
  }
  
  // 处理评论输入
  const handleCommentChange = (e) => {
    setComment(e.detail.value)
  }
  
  // 提交评价
  const handleSubmit = async () => {
    if (!state.currentUser) {
      Taro.showToast({
        title: '请先登录',
        icon: 'none'
      })
      return
    }
    
    if (!userRating) {
      Taro.showToast({
        title: '请选择评分',
        icon: 'none'
      })
      return
    }
    
    setLoading(true)
    
    try {
      // 创建评价数据
      const ratingData: Omit<DishRating, 'id'> = {
        dishId,
        userId: state.currentUser.id,
        userName: state.currentUser.name,
        rating: userRating,
        comment: comment.trim() || undefined,
        createdAt: new Date()
      }
      
      // 保存评价
      const ratingId = await CloudDataManager.addData('ratings', ratingData)
      
      // 如果是新评价，给予积分奖励
      if (!userHasRated) {
        await pointsUtils.processRatingPoints(state.currentUser.id, dishId)
      }
      
      // 更新菜品的平均评分
      await updateDishAverageRating()
      
      Taro.showToast({
        title: '评价成功',
        icon: 'success'
      })
      
      // 回调
      if (onRatingSubmit) {
        onRatingSubmit({
          id: ratingId,
          ...ratingData
        })
      }
      
      // 刷新评价列表
      fetchRatings()
      setShowRatingForm(false)
    } catch (error) {
      console.error('提交评价失败:', error)
      Taro.showToast({
        title: '提交评价失败',
        icon: 'none'
      })
    } finally {
      setLoading(false)
    }
  }
  
  // 更新菜品的平均评分
  const updateDishAverageRating = async () => {
    try {
      // 获取菜品的所有评价
      const ratings = await CloudDataManager.getAllData('ratings', { dishId }) as DishRating[]
      
      if (ratings.length === 0) return
      
      // 计算平均分
      const totalRating = ratings.reduce((sum, rating) => sum + rating.rating, 0)
      const averageRating = totalRating / ratings.length
      
      // 更新菜品数据
      await CloudDataManager.updateData('dishes', dishId, {
        averageRating,
        ratingCount: ratings.length,
        updatedAt: new Date()
      })
    } catch (error) {
      console.error('更新菜品评分失败:', error)
    }
  }
  
  // 渲染星级
  const renderStars = (rating: number, interactive = false) => {
    const stars = []
    
    for (let i = 1; i <= 5; i++) {
      const starClass = i <= rating ? 'star filled' : 'star'
      
      stars.push(
        <View 
          key={i} 
          className={starClass}
          onClick={interactive ? () => handleRatingClick(i) : undefined}
        >
          ★
        </View>
      )
    }
    
    return (
      <View className='stars-container'>
        {stars}
      </View>
    )
  }
  
  // 格式化日期
  const formatDate = (date: Date) => {
    const d = new Date(date)
    return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`
  }
  
  // 计算平均评分
  const calculateAverageRating = () => {
    if (existingRatings.length === 0) return 0
    
    const total = existingRatings.reduce((sum, rating) => sum + rating.rating, 0)
    return total / existingRatings.length
  }
  
  return (
    <View className='dish-rating'>
      {/* 评价汇总 */}
      <View className='rating-summary'>
        <Text className='summary-title'>用户评价</Text>
        {existingRatings.length > 0 ? (
          <View className='summary-content'>
            <Text className='average-rating'>{calculateAverageRating().toFixed(1)}</Text>
            <View className='average-stars'>
              {renderStars(Math.round(calculateAverageRating()))}
            </View>
            <Text className='rating-count'>{existingRatings.length}条评价</Text>
          </View>
        ) : (
          <Text className='no-ratings'>暂无评价</Text>
        )}
      </View>
      
      {/* 评价表单 */}
      {!userHasRated && !showRatingForm && (
        <Button className='rate-button' onClick={() => setShowRatingForm(true)}>
          评价这道菜
        </Button>
      )}
      
      {showRatingForm && (
        <View className='rating-form'>
          <Text className='form-title'>你对{dishName}的评价</Text>
          
          <View className='rating-selector'>
            {renderStars(userRating || 0, true)}
            <Text className='rating-label'>
              {userRating ? `${userRating}星` : '请选择评分'}
            </Text>
          </View>
          
          <Textarea
            className='comment-input'
            value={comment}
            onInput={handleCommentChange}
            placeholder='说说你的体验吧（可选）'
            maxlength={200}
          />
          
          <View className='form-buttons'>
            <Button 
              className='cancel-button' 
              onClick={() => setShowRatingForm(false)}
            >
              取消
            </Button>
            <Button 
              className='submit-button' 
              onClick={handleSubmit}
              loading={loading}
              disabled={!userRating}
            >
              提交评价
            </Button>
          </View>
        </View>
      )}
      
      {/* 已有评价列表 */}
      {showExistingRatings && existingRatings.length > 0 && (
        <View className='existing-ratings'>
          <Text className='section-title'>用户评价</Text>
          
          {existingRatings.map(rating => (
            <View key={rating.id} className='rating-item'>
              <View className='rating-header'>
                <Text className='user-name'>{rating.userName}</Text>
                <Text className='rating-date'>{formatDate(new Date(rating.createdAt))}</Text>
              </View>
              
              <View className='rating-stars'>
                {renderStars(rating.rating)}
              </View>
              
              {rating.comment && (
                <Text className='rating-comment'>{rating.comment}</Text>
              )}
            </View>
          ))}
        </View>
      )}
    </View>
  )
}

export default DishRatingComponent 